package com.wenwen.social.domain.service.Impl;

import com.wenwen.social.domain.model.Follow;
import com.wenwen.social.domain.service.FollowService;

import com.wenwen.social.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Set;

import static com.wenwen.social.constant.FollowConstant.*;

@Service
public class FollowServiceImpl implements FollowService {
	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public Follow queryFollowings(Long uid, Integer page, Integer total) {
		PageUtil pageUtil = new PageUtil(page, total);
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		Set<DefaultTypedTuple> range = zSetOperations.rangeWithScores(getKey(uid),
				pageUtil.getStartNum(), pageUtil.getEndNum());
		if (range == null || range.isEmpty()) {
			return new Follow(uid, new HashMap<>(1));
		}
		HashMap<Long, Long> longLongHashMap = new HashMap<>();
		range.stream().forEach(t -> {
			long key = ((Integer) t.getValue()).longValue();
			long value = t.getScore().longValue();
			longLongHashMap.put(key,value);
		});
		return new Follow(uid, longLongHashMap);
	}

	@Override
	public boolean existFollowings(Long uid, Long followingUid) {
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		Double score = zSetOperations.score(getKey(uid), followingUid);
		if(score!= null && score>0) return true;
		return false;
	}

	@Override
	public void del(Long uid, Long followingUid) {
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		zSetOperations.remove(getKey(uid),followingUid);
	}

	@Override
	public void add(Long uid, Long followingUid) {
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		zSetOperations.add(getKey(uid),followingUid,getNow());
	}

	@Override
	public Long count(Long uid) {
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		return zSetOperations.zCard(getKey(uid));
	}

	private long getNow() {
		return System.currentTimeMillis();
	}

	private String getKey(Long uid) {
		return FOLLOWING_REDIS_PRE+uid;
	}
}
